package com.appclub.kitsilano.calendar;

import com.appclub.kitsilano.R;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

public class CalendarAdapter extends BaseAdapter {
	private Context context;
	private final String[] Values;
	private int griditem;
	private int pposition;

	public CalendarAdapter(Context context, String[] Values, int position) {
		this.context = context;
		this.Values = Values;
		this.pposition = position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View gridView;

		if (convertView == null) {

			gridView = new View(context);

			gridView = inflater.inflate(R.layout.calendar_item, null);

			WindowManager wm = (WindowManager) context
					.getSystemService(Context.WINDOW_SERVICE);
			Display display = wm.getDefaultDisplay();

			int screenWidth = display.getWidth();
			if (screenWidth == 240) {
				griditem = ((screenWidth - dptopx(gridView, 6)) / 7);
			} else {
				griditem = ((screenWidth - dptopx(gridView, 12)) / 7);
			}
			gridView.setLayoutParams(new GridView.LayoutParams(griditem,
					griditem));

			TextView textView = (TextView) gridView
					.findViewById(R.id.text_item);
			textView.setText(Values[position]);
			if (textView.getText() == "0") {
				textView.setText("");
				textView.setBackgroundDrawable(null);
			}
			if (position == pposition) {
				textView.setBackgroundDrawable(context.getResources().getDrawable(
						R.drawable.d_c));
			}
		} else {
			gridView = (View) convertView;
		}

		return gridView;
	}

	private int dptopx(View view, int i) {
		DisplayMetrics dm = new DisplayMetrics();
		dm = view.getResources().getDisplayMetrics();

		int dp2px = (int) (i * dm.density + 0.5f);

		return dp2px;
	}

	public int getCount() {
		return Values.length;
	}

	public Fragment getItem(int position) {
		return CalendarFragment.newInstance(Values[position % Values.length]);
	}

	public long getItemId(int position) {
		return 0;
	}
}